import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/bean/music_persional.dart';
import 'package:flutter_bsbdj/pagers/music/music_suspension_window.dart';
import 'package:flutter_bsbdj/utils/toast.dart';

class MusicDetail extends StatefulWidget {
  PersonalItem _item;
  List<PersonalItem> allMusic;
  int playIndex;

  MusicDetail(this._item, {this.allMusic, this.playIndex});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return DetailWidget();
  }
}

class DetailWidget extends State<MusicDetail> {
  String lrc = "";
  List<String> _lrc_list = [];
  List<Lrc> _lrcText = [];
  double _lrc_item_hight;
  ScrollController _lrcController = ScrollController();
  int _currentIndex = 0;
  int _duration = 1;
  int _prosition = 0;
  String _positionText = "00:00";
  String _durationText = "00:00";
  AudioPlayerState _playerState = AudioPlayerState.PLAYING;
  int playIndex;
  String title = "";
  double screenWidth;
  bool isSeekbarChange = false;
  double _seekValue = 0.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    playIndex = widget.playIndex;
    initLrc(widget._item.lrc);
    MusicWindowPlay.getInstance(context).musicPlayInfoListener(
        onPlayerStateChanged,
        onPlayerError,
        onDurationChanged,
        onAudioPositionChanged,
        onPlayerCompletion);
    _lrcController.addListener(() {});
    setState(() {
      _playerState = MusicWindowPlay.getInstance(context).getPlayState();
      title = widget._item.title;
    });
  }

  //播放状态变化监听
  void onPlayerStateChanged(AudioPlayerState state) {
    print("$state + onPlayerStateChanged");
    setState(() {
      _playerState = state;
    });
  }

  //播放错误
  void onPlayerError(String string) {}

  //歌曲总时长变化监听
  void onDurationChanged(Duration dur) {
    if (_duration != dur.inMilliseconds) {
      setState(() {
        _duration = dur.inMilliseconds;
        _durationText = dur.toString().substring(2, 7);
      });
    }
  }

  //歌曲播放当前位置监听
  void onAudioPositionChanged(Duration dur) {
    int pos = dur.inMilliseconds;
    setState(() {
      _prosition = dur.inMilliseconds;
      _positionText = dur.toString().substring(2, 7);
      if (_lrcText != null && _lrcText.length > 0) {
        if (_currentIndex < _lrcText.length - 1 &&
            pos >= _lrcText[_currentIndex + 1].time) {
          _currentIndex++;
          _lrcController.position.moveTo(
              _lrc_item_hight / 9 * (_currentIndex - 3),
              duration: Duration(milliseconds: 600));
        }
      }
    });
  }

  //播放完成监听
  void onPlayerCompletion() {
    setState(() {
      _currentIndex = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    screenWidth = MediaQuery.of(context).size.width;
    _lrc_item_hight = MediaQuery.of(context).size.height - 225;
    return WillPopScope(
        child: Stack(
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Image.asset(
                "images/timg.jpg",
                fit: BoxFit.cover,
              ),
            ),
            Column(
              children: <Widget>[
                //标题
                Container(
                  margin: EdgeInsets.only(top: 25),
                  height: 50,
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        child: Container(
                          width: 60,
                          height: 50,
                          alignment: Alignment.center,
                          child: Icon(
                            Icons.arrow_back_ios,
                            size: 20,
                            color: Colors.white,
                          ),
                        ),
                        onTap: () {
                          Navigator.of(context).pop();
                          MusicWindowPlay play =
                              MusicWindowPlay.getInstance(context);
                          if (play.musicIsPlaying()) {
                            play.isHeidden(false);
                          }
                        },
                      ),
                      Expanded(
                          child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          widget._item.title,
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              decoration: TextDecoration.none),
                        ),
                      )),
                      Container(
                        width: 60,
                      )
                    ],
                  ),
                ),
                //歌词
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: _lrc_item_hight,
                  child: GestureDetector(
                    child: _initLrcList(),
                  ),
                ),
                //进度条
                Container(
                  height: 10,
                  margin: EdgeInsets.only(bottom: 10, top: 20),
                  width: screenWidth,
                  child: Scaffold(
                    backgroundColor: Color(0x00000000),
                    body: Slider(
                      value:
                          isSeekbarChange ? _seekValue : _prosition.toDouble(),
                      min: 0.0,
                      max: _duration.toDouble(),
                      onChanged: (value) {
                        if (isSeekbarChange) {
                          setState(() {
                            _seekValue = value;
                          });
                        }
                      },
                      onChangeEnd: (value) {
                        print("MusicDetail onChangeEnd   $value");
                        setState(() {
                          isSeekbarChange = false;
                          _seekValue = value;
                          _prosition = value.toInt();
                          MusicWindowPlay.getInstance(context)
                              .seekTo(_seekValue.toInt());
                          for (int i = 0; i < _lrcText.length; i++) {
                            if (_lrcText[i].time >= _prosition) {
                              print(
                                  "MusicDetail ${_lrcText[i].time}  $_prosition");
                              _currentIndex = i - 1;
                              break;
                            }
                          }
                          _lrcController.position.moveTo(
                              _lrc_item_hight / 9 * (_currentIndex - 5));
                        });
                      },
                      onChangeStart: (value) {
                        print("MusicDetail onChangeStart   $value");
                        setState(() {
                          isSeekbarChange = true;
                          _seekValue = value;
                        });
                      },
                      activeColor: Colors.blueAccent,
                      inactiveColor: Colors.green,
                    ),
                  ),
                ),
                //时间 00:00          04:50
                Container(
                  margin: EdgeInsets.only(left: 20, right: 20),
                  height: 14,
                  child: Row(
                    children: <Widget>[
                      Text(
                        _positionText,
                        style: TextStyle(
                            fontSize: 12,
                            color: Colors.white,
                            decoration: TextDecoration.none),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.centerRight,
                          child: Text(
                            _durationText,
                            style: TextStyle(
                                fontSize: 12,
                                color: Colors.white,
                                decoration: TextDecoration.none),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                //控制 |<   ||   >|
                Container(
                  margin: EdgeInsets.only(left: 50, right: 50),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                          child: GestureDetector(
                        child: Container(
                          alignment: Alignment.center,
                          height: 60,
                          child: Icon(
                            Icons.skip_previous,
                            color: Colors.white,
                            size: 60,
                          ),
                        ),
                        onTap: () {
                          if (widget.allMusic != null &&
                              widget.allMusic.length > 1) {
                            if (playIndex == 0) {
                              Toast.toast(context, "这是第一首歌");
                            } else {
                              setState(() {
                                playIndex--;
                                _prosition = 0;
                                _duration = 1;
                                _currentIndex = 3;
                                _positionText = "00:00";
                                _durationText = "00:00";
                                initLrc(widget.allMusic[playIndex].lrc);
                                title = widget.allMusic[playIndex].title;
                                MusicWindowPlay.getInstance(context).playMusic(
                                    widget.allMusic[playIndex].url,
                                    widget.allMusic[playIndex],
                                    context);
                              });
                            }
                          } else {
                            Toast.toast(context, "这是第一首歌");
                          }
                        },
                      )),
                      Expanded(
                          child: GestureDetector(
                        child: Container(
                          alignment: Alignment.center,
                          height: 60,
                          child: Icon(
                            _playerState == AudioPlayerState.PLAYING
                                ? Icons.pause_circle_outline
                                : Icons.play_circle_outline,
                            color: Colors.white,
                            size: 60,
                          ),
                        ),
                        onTap: () {
                          print("$_playerState + playcontrollor");
                          if (_playerState == AudioPlayerState.PLAYING) {
                            MusicWindowPlay.getInstance(context).pause();
                          } else {
                            try {
                              MusicWindowPlay.getInstance(context).rePlay();
                            } catch (e) {
                              MusicWindowPlay.getInstance(context).playMusic(
                                  widget._item.url, widget._item, context);
                            }
                          }
                        },
                      )),
                      Expanded(
                        child: GestureDetector(
                          child: Container(
                            alignment: Alignment.center,
                            height: 60,
                            child: Icon(
                              Icons.skip_next,
                              color: Colors.white,
                              size: 60,
                            ),
                          ),
                          onTap: () {
                            if (widget.allMusic != null &&
                                widget.allMusic.length > 1) {
                              if (playIndex == widget.allMusic.length - 1) {
                                Toast.toast(context, "这是最后一首歌");
                              } else {
                                setState(() {
                                  playIndex++;
                                  _prosition = 0;
                                  _duration = 1;
                                  _positionText = "00:00";
                                  _durationText = "00:00";
                                  initLrc(widget.allMusic[playIndex].lrc);
                                  title = widget.allMusic[playIndex].title;
                                  MusicWindowPlay.getInstance(context)
                                      .playMusic(widget.allMusic[playIndex].url,
                                          widget.allMusic[playIndex], context);
                                });
                              }
                            } else {
                              Toast.toast(context, "这是最后一首歌");
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ],
        ),
        onWillPop: () {
          Navigator.popAndPushNamed(context, "music_detail");
        });
  }

  //歌词列表
  Widget _initLrcList() {
    if (_lrcText == null || _lrcText.length == 0) {
      return Center(
        child: Text(
          "暂无歌词",
          style: TextStyle(
              fontSize: 14,
              color: Colors.white,
              decoration: TextDecoration.none),
        ),
      );
    } else {
      return ListView.builder(
        itemCount: _lrcText.length,
        itemBuilder: (content, index) {
          return Container(
            height: _lrc_item_hight / 9,
            alignment: Alignment.bottomCenter,
            margin: EdgeInsets.only(top: 1),
            padding: EdgeInsets.only(top: 8),
            child: Text(
              _lrcText[index].text,
              style: _lrcTextStyle(index),
            ),
          );
        },
        controller: _lrcController,
      );
    }
  }

  //歌词的文字格式
  TextStyle _lrcTextStyle(int index) {
    if (index == _currentIndex) {
      return TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.bold,
        color: Colors.green,
        decoration: TextDecoration.none,
      );
    } else {
      return TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.normal,
        color: Colors.white,
        decoration: TextDecoration.none,
      );
    }
  }

  //提取歌词列表以及每一句歌词对应的时间
  void initLrc(String lrcs) {
    print(lrcs);
    if (lrc != lrcs) {
      if (lrcs.isEmpty || lrcs.length < 20) {
      } else {
        List<String> lrc_t = lrcs.split("[");
        List<Lrc> lrctext = [];
        lrctext.add(Lrc(time: 0.0, text: ""));
        lrctext.add(Lrc(time: 0.0, text: ""));
        lrctext.add(Lrc(time: 0.0, text: ""));
        for (int i = 0; i < lrc_t.length; i++) {
          List<String> y = lrc_t[i].split("]");
          if (y.length >= 2) {
            String time = y[0];
            double t = 0;
            if (time != null && time.startsWith("0") && time.length > 6) {
              t = double.parse(time.substring(0, 2)) * 60 * 1000 +
                  double.parse(time.substring(3, 5)) * 1000 +
                  double.parse(time.substring(6, time.length));
            }
            lrctext.add(Lrc(text: y[1].trimLeft(), time: t));
          }
        }
        double t = lrctext[lrctext.length - 1].time;
        for (int i = 0; i < 3; i++) {
          lrctext.add(Lrc(time: t, text: ""));
        }
        setState(() {
          lrc = lrcs;
          _lrcText = lrctext;
        });
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //退出页面终止监听
    MusicWindowPlay.getInstance(context)
        .musicPlayInfoListener(null, null, null, null, null);
  }
}

class Lrc {
  double time;
  String text;

  Lrc({this.time, this.text});
}
